<template>
<div>
  <div class="topbar" ref="topbar">
    <div class="left">今日舆情</div>
    <div class="right">
      <div class="top">
        <div class="lineinfo">
          <div class="lineinfoItem">
            <span class="title">今日总量：</span>
            <span class="num">{{plusMinus.totals}}</span>
          </div>
          <div class="lineinfoItem">
            <span class="title">负面占比:</span>
            <span class="num">{{ratio == 'NaN' ? 0 : parseInt(ratio*100)}}%</span>
          </div>
        </div>
        <SlideSwitch v-show="switchArr!=''" v-on:getdown="getdown()" v-on:getface="getface()" v-on:getmoddle="getmoddle()" class="switch" :data="switchArr"></SlideSwitch>
      </div>
      <div class="bottom">
        <div class="medium" v-for="(item, i) in webSite" :key="i">
          <div class="num">{{item.doc_count}}</div>
          <div class="title">
            <!-- <img class="img" :src="require(`./img/medium-${imgs[item.websiteName]}.png`)"/> -->
            <span class="label">{{item.websiteName}}</span>
          </div>
        </div>
      </div>
    </div>
  </div>
  <div class="modules m-gridup" ref="modules">
      <Module v-for="item in modulesLimit" :data = "item" :key="item.id" v-show = "item.overdue!=0"></Module>
  </div>
</div>

</template>

<script>
import $ from 'jquery'
import {range,throttle} from 'utils'
import SlideSwitch from 'components/common/SlideSwitch'
import Module from './Module'
let imgs = {'新闻':'news',
            '论坛':'forum',
            '微博':'microblog',
            '平面媒体':'print',
            '博客':'blog',
            '贴吧':'postbar',
            '推特':'twitter',
            '微信':'wechat',
            '招标':'invite',
            '手机app':'app',
            '笑话':'joke'}
let startTime = 1
export default {
  name: 'home',
  components: {Module, SlideSwitch},
  data(){
    return {
      imgs,
      switchArr:[],
      plusMinus:[],
      information:[],
      modules:[],
      positiveOrNegative:2,
      myArray:[1,2,3,4,5,6,7,8,9],
      plus:{
        clickFlag:true,
        count:0
      },
      ratio:0,
      webSite:[],
      webSiteA:[],//负面
      webSiteB:[],//正面
      webSiteC:[]//中性
    }
  },
  mounted() {
    this.getTodayOpinion()
    this.getWebSite()
    this.getHomeModul()
  },
  computed:{
      // 模块显示限制最多四个
      modulesLimit:function(){
        if(this.modules.length>6)
            return this.modules.slice(0,6)
          else
            return this.modules
      }
  },
  methods:{
    // 正负面
    async getTodayOpinion(){
      let r = await this.$http.get('vrv-monitor-platform-web/data/queryTodayOpinion?aggsField=positiveOrNegative')
      this.plusMinus = r.body.data
      this.getList()
    },
    //载体类型
    getWebSite(){
      let arr = [0,1,2]
      let reqs = arr.map(d => {
        return this.$http.get('vrv-monitor-platform-web/data/queryTodayOpinion?aggsField=webSiteType&positiveOrNegative=' + d)
      })
      Promise.all(reqs).then(r=>{
        this.webSiteA = r[2].body.data
        this.webSiteB = r[1].body.data
        this.webSiteC = r[0].body.data
        this.webSite = this.webSiteA
      })
    },
    // 正负面数据转换
    getList:function(){
      if(this.plusMinus.length==0){
        this.switchArr=[
          {label: '负面: 0', color: '#e85d4b'},
          {label: '正面: 0', color: '#6ccac8'},
          {label: '中性: 0', color: '#ff9000'}
        ]
        return
      }
      this.plusMinus.totals = 0;
      this.plusMinus.negative = this.plusMinus.filter(d=>d.key == 0)[0].doc_count//中性
      this.plusMinus.positive = this.plusMinus.filter(d=>d.key == 1)[0].doc_count//正面
      this.plusMinus.neutral = this.plusMinus.filter(d=>d.key == 2)[0].doc_count//正面
      this.plusMinus.totals = this.plusMinus.map(d=> d.doc_count).reduce((a,c)=> a+c, 0) //总数
      this.ratio = (this.plusMinus.neutral/this.plusMinus.totals).toFixed(2)
      let neutral = this.plusMinus.neutral===undefined?0:this.plusMinus.neutral
      let positive = this.plusMinus.positive===undefined?0:this.plusMinus.positive
      let negative = this.plusMinus.negative===undefined?0:this.plusMinus.negative
      this.switchArr=[
        {label: '负面:' + neutral, color: '#e85d4b'},
        {label: '正面:' + positive, color: '#6ccac8'},
        {label: '中性:' + negative, color: '#ff9000'}
      ]
    },
    // 获取模块
    async getHomeModul(){
      let r = await this.$http.post('/vrv-monitor-platform-web/module/queryByOrgCodeHome',{home:1})
      this.modules = r.body.data
      this.modules = this.modules.filter(d => d.overdue != 0)
      this.$nextTick(function(){
        this.modules.length>0 &&  this.make()
      })
    },
    // 负面
    getdown(){
      this.webSite = this.webSiteA
      console.log('s')
    },
    // 正面
    getface(){
      this.webSite = this.webSiteB
    },
    // 中性
    getmoddle(){
      this.webSite = this.webSiteC
    },
    //首页排序
    changeSeq(arr){
      this.$http.post('vrv-monitor-platform-web/module/changeSeq',{
        ids:arr.join(',')
      }).catch(d=>{
        this.$message.error("错误")
      })
    },
    // 页面动画
    make(){
      let lists = this.$refs.menuItem
      let topbar = this.$refs.topbar
      let w =  $(topbar).width()
      let _this = this
      $(lists).each(function(i, el){
        el.style.background = `hsl(${Math.random() * 360}, 60%, 70%)`
      })
      $.fn.gridup = function(
        {
        width = (w-20)/2,
        height = 381,
        wgap = 20,
        hgap = 20,
        colnum = 2,
        transition = 500,
        data = []
      } = {}){
        let m = document.body.clientWidth
        if(m<1600&m>1300){
          height = 358
        }else if(m<1300){
          height = 308
        }
        let $el = this.eq(0)
        let $bg = $('<div class="m-gridup-bg"></div>')
        let $items = $el.children()
        let len = $items.length
        let $tmp
        let elpos
        let mdpos
        let mdflag = false
        let mz = 10
        let timer = {last: 0, curr: +new Date()}
        let getTopLeft = function({col, row}){
          return {
            left: col * (width + wgap),
            top: row * (height + hgap)
          }
        }
        $el.addClass('m-gridup')
        $el.css({
          width: colnum * (width + wgap) - wgap,
          height: Math.ceil(len / colnum) * (height + hgap) - hgap
        })
        $bg.css({width,height})
        $el.prepend($bg)
        elpos = $el.offset()
        if(data.length >= len){
          $items.each((i, el) => $(el).data('d', data[i]))
        }
        $items.addClass('m-gridup-item')
        $items.css({
          width,
          height,
          transitionDuration: transition + 'ms'
        })
        $items.each(function(i, el){
          let row = Math.floor(i / colnum)
          let col = i % colnum
          let $el = $(el)
          $el.css(getTopLeft({col, row}))
          $el.data('pos', {row, col})
        })
        $items.on('mousedown', function(e){
          $tmp = $(this)
          let tmppos = $tmp.position()
          $bg.css(getTopLeft($tmp.data('pos')))
          mdpos = {
            x:e.pageX - tmppos.left,
            y:e.pageY - tmppos.top
          }
          $el.css('cursor', '-webkit-grab')
          $tmp.css('transition-duration', '0ms')
          $tmp.css('z-index', mz++)
          mdflag = true
        })
        $el.on('mousemove', function(e){
          if(mdflag){
            let offset = {
              top: e.pageY - mdpos.y,
              left: e.pageX - mdpos.x
            }
            $tmp.css(offset)
            timer.curr = +new Date()
            if(timer.curr - timer.last > 100){
              timer.last = timer.curr
              $items.each(function(i, e){
                let $e = $(e)
                let tpos = $tmp.data('pos')
                let epos = $e.data('pos')
                if(tpos.row == epos.row && tpos.col == epos.col) return
                let toff = getTopLeft(tpos)
                let eoff = getTopLeft(epos)
                let ch = height - Math.abs(eoff.top - offset.top)
                let cw = width - Math.abs(eoff.left - offset.left)
                if(ch > 0 && cw > 0 && ch * cw > width * height * 2 / 5){
                  $e.css(toff)
                  $bg.css(eoff)
                  $tmp.data('pos', epos)
                  $e.data('pos', tpos)
                }
              })
            }
          }
        })
        $el.on('mouseup', function(){
          $el.css('cursor', '')
          mdflag = false
          let pos = getTopLeft($tmp.data('pos'))
          $tmp.css(pos)
          $tmp.css('transition-duration', transition + 'ms')
          if(JSON.stringify(arr) != JSON.stringify(grid.getSorted())){
            arr = grid.getSorted()
            _this.changeSeq(grid.getSorted())
          }
        })
        return {
          getSorted(){
            return Array.from($items)
              .map(d => {
                let pos = $(d).data('pos')
                return {
                  row: pos.row,
                  col: pos.col,
                  data: $(d).data('d')
                }
              }).sort((a, b) => a.row == b.row ? a.col - b.col : a.row - b.row)
              .map(d => d.data)
          }
        }
      }
      let modules = this.$refs.modules
      let arr = this.modulesLimit.map(v => v.id)
      let grid = $(modules).gridup({
        data: arr
      })
    }
  },
}
</script>
<style lang="stylus">
.m-gridup-bg
  border 3px dashed #ccc
  border-radius 0.4rem
  box-sizing border-box
  z-index 1
  position absolute
  left 0
  top 0
</style>
<style lang="stylus">

.topbar
  background white
  height 11.75rem
  display flex
  border-radius 0
  overflow hidden
  margin-bottom 1.25rem
  margin-right 1.3rem
  user-select  none
.topbar>.left
  flex: none
  width: 4.75rem
  writing-mode vertical-lr
  color white
  font-size 1.3rem
  letter-spacing .2rem
  text-align center
  padding-left 1.5rem
  color #e75a46
  border-left 5px solid #e75a46
  box-sizing border-box

.topbar>.right
  flex auto

.topbar>.right>.top
  position relative
  height 3.93rem
  border-bottom 1px solid #eeeeee
  >.lineinfo
    position absolute
    top 1.38rem
    left 3.56rem
    >.lineinfoItem
      font-size 0.88rem
      display inline-block
      margin-right 3.75rem
      >.title
        color #666666
        font-size 18px;
      >.num
        font-size 1.375rem
      &:last-child
        color #e75246
  >.switch
    position absolute
    top 1.00rem
    right 3.62rem

.topbar>.right>.bottom
  display flex
  >.medium
    flex auto
    margin-top .9rem
    text-align center
    border-right 1px solid #dcdcdc
    height 6.00rem
    padding-top 0.42rem
    &:nth-last-child(1)
      border-right 0
    >.num
      font-family PingFang-SC-Medium
      font-size 2.25rem
      padding-bottom 0.50rem
      color #565656
    >.title
      font-size 0.88rem
      color #666666
      line-height 1.75rem
      >.img
        height 1.75rem
        width 1.75rem
        vertical-align middle
        margin-right 1rem
.modules
  position relative
.m-gridup 
  position relative
.m-gridup-item 
  position absolute
  transition all .6s ease
  z-index 5


</style>
